<?php
class store {
	private $_name;

	/**
	 * Constructor
	 *
	 * @param string $name store name
	 */
	public function __construct($name = "default") {
		if (!isset($_SESSION)) session_start();
		$this->_name = $name;
		if (isset($_SESSION[$this->_name]) && !is_array($_SESSION[$this->_name])) $this->clear();
	}

	/**
	 * Clear store or variable from store
	 *
	 * @param mixed $var_name variable name, if null then store will be cleared
	 */
	public public function clear($var_name = null) {
		if($var_name === null) {
			if(isset($_SESSION[$this->_name])) unset($_SESSION[$this->_name]);
		} else {
			if(isset($_SESSION[$this->_name][$var_name])) unset($_SESSION[$this->_name][$var_name]);
		}
	}

	/**
	 * Put valiable to store
	 *
	 * @param mixed $var variable name or array
	 * @param mixed $val valiable value or null if $var is array
	 */
	public function put($var, $val = null) {
		if(!is_array($var)) {
			$_SESSION[$this->_name][$var] = $val;
		} else {
			foreach($var as $key => $val) $this->put($key, $val);
		}
	}

	/**
	 * Put array to store
	 *
	 * @param string $var variable name
	 * @param array $val valiable value or null if $var is array
	 */
	public function put_array($var, $val = null) {
		if(!is_array($val)) return;
		$_SESSION[$this->_name][$var] = $val;
	}

	/**
	 * Check if the variable is in store
	 *
	 * @param string $var_name variable name
	 * @return true if set, false otherwise
	 */
	public function is_set($var_name) {
		return isset($_SESSION[$this->_name][$var_name]);
	}

	/**
	 * Define variable in store
	 *
	 * @param variable name $var
	 * @param variable value $val
	 */
	public function put_def($var, $val=null) {
		if(!is_array($var)) {
			if(!$this->is_set($var)) $this->put($var);
		} else {
			foreach($var as $key=>$val) $this->put_def($key, $val);
		}
	}

	/**
	 * Get value from store by variable name
	 *
	 * @param string $var_name variable name
	 * @param mixed $def_val default value if variabe $var_name is not set in store
	 * @return variable $var_name value
	 */
	public function get($var_name=null, $def_val = '') {
		if($var_name === null) {
			return isset($_SESSION[$this->_name]) && is_array($_SESSION[$this->_name]) ? $_SESSION[$this->_name] : array();
		} else {
			return $this->is_set($var_name) ? $_SESSION[$this->_name][$var_name] : $def_val;
		}
	}

	/**
	 * Check if store or variable is empty
	 *
	 * @param string $var_name variable name, if null check store
	 * @return true if empty, false otherwise
	 */
	public function is_empty($var_name = null)	{
		if($var_name === null) return empty($_SESSION[$this->_name]);
		else return empty($_SESSION[$this->_name][$var_name]);
	}
}
?>